package com.itheima.controller;


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
@RequestMapping("uploadController")
public class UploadController {

    @RequestMapping("/upload")
    @ResponseBody
    public void doUpload(MultipartFile[] files, HttpServletRequest req) throws IOException {
        for (MultipartFile file : files) {
            if (!file.isEmpty()){  //判断文件是否为null; 为null则为true所以取反
                //获取servlet上下文对象;
                ServletContext servletContext = req.getServletContext();
                //通过上下文对象获取webapp下在img目录在服务器部署后的绝对路径
                String realPath = servletContext.getRealPath("/img");
                System.out.println(realPath);

                //获取图片的全名称
                String originalFilename = file.getOriginalFilename();
                System.out.println(originalFilename);

                //使用UUID随机创建唯一名称
                String s = UUID.randomUUID().toString();
                //System.out.println(s);//783388d3-0866-4073-94c8-e74aa20f69ba
                String s1 = s.replaceAll("-", "");//通过将"-"替换为""这个字符串; 从而将"-"去掉
                System.out.println(s1);//3452e9e6c87e494aa0e442492ae42c05

                //获取原始图片的后缀
                String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
                System.out.println(substring);//.jpg  (这里直接获得了最后面的后缀)

                //创建新的唯一名称
                String s2 = s1 + substring;

                //将图片存储到目录中
                file.transferTo(new File(realPath,s2));
            }
        }

    }
}
